package com.crm.controller;

import com.crm.constant.Constant;
import com.crm.pojo.SalChance;
import com.crm.pojo.SalPlan;
import com.crm.pojo.User;
import com.crm.service.salChance.SalChanceService;
import com.crm.service.salPlan.SalPlanService;
import com.crm.service.user.UserService;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/chance")
public class SalChanceController {
    @Resource
    private SalChanceService salChanceService;
    @Resource
    private SalPlanService salPlanService;
    @Resource
    private UserService userService;

    //当前端页面传过来的的String类型的日期与后台实体类的Date类型不匹配时，需要加上该方法
    @InitBinder
    public void init(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    /**
     * 获取销售机会列表
     * @param custName 客户名称
     * @param chcTitle 概述
     * @param pageIndex 首页
     * @param model 模板
     * @return 返回一个路径字符串
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    public String list(
            @RequestParam(required = false) String custName, @RequestParam(required = false) String chcTitle,
            @RequestParam(required = false, defaultValue = "1") int pageIndex, Model model
    ) throws Exception {
        Sort sort = Sort.by(Sort.Direction.ASC, "chcId");
        Pageable pageable = PageRequest.of(pageIndex-1, 5, sort);
        Map param = new HashMap();

        if (custName != null && !custName.equals(""))
            param.put("chcCustName", custName);
        if (chcTitle != null && !chcTitle.equals(""))
            param.put("chcTitle", chcTitle);

        Page<SalChance> salChancePage = salChanceService.findSalChancePageByMap(param, pageable);

        model.addAttribute("salChancePage", salChancePage);
        model.addAttribute("custName", custName);
        model.addAttribute("chcTitle", chcTitle);

        return "chance/list";
    }

    /**
     * 获取指定销售机会信息详情
     * @param chcId 销售机会编号
     * @param model 模块
     * @return 返回一个路径字符串
     * @throws Exception
     */
    @RequestMapping(value = "/detail/{chcId}")
    public String findSalChance(@PathVariable Long chcId, Model model) throws Exception {
        SalChance salChance = salChanceService.findSalChanceById(chcId);
        List<User> userList = userService.findUsersByRoleName();

        model.addAttribute("salChance", salChance);
        model.addAttribute("userList", userList);

        return "chance/edit";
    }

    /**
     * 修改指定销售机会信息
     * @param salChance 销售机会
     * @return 返回一个路径字符串
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    public String editSalChance(SalChance salChance) throws Exception {
        salChance = salChanceService.editSalChance(salChance);

        if (salChance != null) {
            return "redirect:/chance/list";
        } else {
            return "chance/edit";
        }
    }

    /**
     * 删除指定销售机会信息
     * @param chcId 销售机会编号
     * @return 返回一个 Map 集合
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/del/{chcId}")
    public Map delSalChance(@PathVariable Long chcId, HttpSession session) throws Exception {
        Map resultMap = new HashMap();

        List<SalPlan> salPlanList = salPlanService.findSalPlansByChcId(chcId);

        if (salPlanList == null || salPlanList.size() == 0) {
            if (salChanceService.delSalChance(chcId) > 0) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        } else {
            if (salPlanService.delSalPlanByPlaChcId(chcId) > 0) {
                if (salChanceService.delSalChance(chcId) > 0) {
                    resultMap.put("delResult", "true");
                } else {
                    resultMap.put("delResult", "false");
                }
            } else {
                resultMap.put("delResult", "false");
            }
        }

        return resultMap;
    }

    /**
     * 跳转到添加页面
     * @param model 模块
     * @param session
     * @return 返回一个字符串路径
     * @throws Exception
     */
    @RequestMapping(value = "/toAdd")
    public String toAdd(Model model, HttpSession session) throws Exception {
        List<User> userList = userService.findUsersByRoleName();
        User user = userService.findUserByRoleNameAndUsrId(((User)session.getAttribute(Constant.LOGIN_USER)).getUsrId());

        model.addAttribute("userList", userList);
        model.addAttribute("user", user);

        return "chance/add";
    }

    /**
     * 添加一条销售机会信息
     * @param salChance 销售机会信息
     * @param session
     * @return 返回一个字符串路径
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    public String addSalChance(SalChance salChance, HttpSession session) throws Exception {
        salChance.setChcCreateId(((User)session.getAttribute(Constant.LOGIN_USER)).getUsrId());
        salChance.setChcCreateBy(((User)session.getAttribute(Constant.LOGIN_USER)).getUsrName());
        salChance.setChcCreateDate(new Date(new java.util.Date().getTime()));

        if (salChance.getChcDueId() == null) {
            salChance.setChcStatus("1");
        } else {
            salChance.setChcStatus("2");
        }

        salChanceService.addSalChance(salChance);

        return "redirect:/chance/list";
    }

    @ResponseBody
    @RequestMapping(value = "/edit/chcStatus")
    public Integer editSalChanceByChcIdAndChcStatus(Long chcId, String chcStatus) throws Exception {
        int ret = 0;

        if (salPlanService.findSalPlanByPlaChcIdIsNull(chcId) > 0) {
            ret = -1;
        } else {
            ret = salChanceService.editSlaChanceByChcIdAndChcStatus(chcStatus, chcId);
        }

        System.out.println(ret);

        return ret;
    }
}